<?php
declare (strict_types=1);

namespace app\services\adv;

use app\services\BaseServices;
use app\dao\adv\AdvDao;
use crmeb\exceptions\AdminException;
use think\db\exception\{DataNotFoundException, DbException, ModelNotFoundException};

/**
 *
 * Class AdvServices
 * @package app\services\adv
 * @mixin AdvDao
 */
class AdvServices extends BaseServices
{

    /**
     * AdvServices constructor.
     * @param AdvDao $dao
     */
    public function __construct(AdvDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * @param array $where
     * @param array $field
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getList(array $where, array $field = ['*']): array
    {
        [$page, $limit] = $this->getPageValue();
        $list = $this->dao->getList($where, $field, $page, $limit);
        $count = $this->dao->count($where);
        return compact('list', 'count');
    }

    /**
     * @param array $where
     * @param array $field
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getAllList(array $where = [], array $field = ['*']): array
    {
        return $this->dao->getList($where, $field);
    }

    /**
     * @param string $title
     * @param int $num
     * @param string $pixel
     * @param int $id
     * @return int
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function setAdv(string $title, int $num, string $pixel, int $id = 0): int
    {
        if ($id) {
            /** @var AdvDao $adv */
            $adv = $this->dao->get($id);
            $adv->save([
                'title' => $title,
                'num' => $num,
                'pixel' => $pixel
            ]);
            return $adv->id;
        }
        /** @var AdvServices $res */
        $res = $this->dao->save(compact('title', 'num', 'pixel'));
        return intval($res->id);
    }

    /**
     * @param int $id
     * @return mixed
     */
    public function delAdv(int $id)
    {
        if (!$id) {
            throw new AdminException('请传入id');
        }
        return $this->dao->delete($id);
    }
}
